#!/usr/bin/python
import serial
import os
from time import sleep

from django.conf import settings

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# settings.configure(
#   DATABASE_ENGINE='django.db.backends.sqlite3',
#   DATABASE_HOST="localhost",
#   DATABASE_NAME=os.path.join(BASE_DIR, "brewmaster.db"),
#   DATABASE_USER="kuchenbecker",
#   DATABASE_PASSWORD="brewmeister",
#   DATABASE_PORT="5432",
#   INSTALLED_APPS="brewery",
# )
settings.configure(
    DATABASES={ 'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, "brewmaster.db"),
        'USER': 'kuchenbecker',
        'PASSWORD': 'brewmeister',
        'HOST': '',
        'PORT': '',
        }, },
    TIME_ZONE='Europe/Luxembourg'
)

from server_state import ServerState

class ArduinoServer:
  """The server continuously reads from serial to update the state variables
  and writes settings to serial"""

  def __init__(self):
    self._running = True
    self._server_state = ServerState()
    self._server_state.ResetToDefaults()

    # Signals from Arduino
    # Temp 1
    # Temp 2
    # Temp 3

    # Commands to Server
    # PLevel
    # Pump On / Off


  def ProcessInput(self, lines):
    # do something with the lines
    mash_temp, boil_temp, stream_temp = None, None, None
    for line in lines:
      line.strip()
      keyval = line.split(':')
      if(len(keyval) != 2):
        continue
      key, value = keyval
      if (key == 'mash'):
        mash_temp = int(value)
      if (key == 'boil'):
        boil_temp = int(value)
      if (key == 'stream'):
        stream_temp = int(value)
      if mash_temp is not None and boil_temp  is not None and stream_temp  is not None:  # case where they are set multiple times
        break
    print(lines)
    self._server_state.SetTemp(mash_temp, boil_temp, stream_temp)
    return

  def GetOutput(self):
    power_level = self._server_state.ManageStateViaSettingsAndTemperature()
    pump_on = self._server_state.IsPumpOn()
    return '{0}.{1}\r'.format(power_level, pump_on)


def main():

  debug = False
  server = ArduinoServer()
  if not debug:
    com_serial = serial.Serial('/dev/ttyUSB0', 9600)
  while server._running:
    if not debug:
      print('Read lines.')
      lines = []
      try:
        i = 0
        while i < 6:
          i += 1
          line = com_serial.readline()
          lines.append(line)



      except Exception:
        pass
      server.ProcessInput(lines)
    output = server.GetOutput()
    print(output)
    if not debug:
      com_serial.write(output)
      com_serial.flush()

    sleep(1)


if  __name__ == '__main__':main()



